const express = require("express");
const fs = require("fs");
const url = require("url");
const bodyParser = require("body-parser");

//创建服务器
const server = express();

//引入html
server.get("/",(request,response)=>{
    fs.readFile("./html/index.html",(error,info)=>{
        response.write(info);
        response.end();
    })
})



//对ajax进行处理
server.get("/api/login",(request,response)=>{
    let urlobj = url.parse(request.url,true);
    console.log(urlobj)
    //响应一个json对象response.json({})
    //内部有end()  不需要再外面发送
    //express对response进行拓展
    //.status(500)服务器报错
    response.status(500).json({
        status: 0,
        message: "登录成功",
        data: {}
    })
})

//bodyParser.urlencoded()中间件内部调用next()   处理post请求的body参数
server.use("/api/login",bodyParser.urlencoded())

server.post("/api/login",(request,response)=>{

    //post请求数据在request.body中
    console.log(request.body)

    response.status(500);
    response.json({
        status: 0,
        message: "登录成功",
        data: {}
    })
})


//处理静态资源文件
server.use("/static",express.static(__dirname+"/static"))

//启动服务器 开始监听
server.listen(8080,"localhost",(error)=>{
    if(!error){
        console.log("启动成功")
    }else{
        console.log("启动失败")
        console.log(error)
    }
})